import os
import re
import uuid
from datetime import timedelta, datetime

from fastapi import APIRouter, Form, HTTPException, Depends, UploadFile, File
from fastapi.security import OAuth2PasswordRequestForm
from jose import jwt
from requests import Session

from auth import pwd_context, SECRET_KEY
from db import get_db, SessionLocal
from models import Root

router = APIRouter(prefix="/api/root", tags=["超级用户"])
@router.post("/login")
def login(phone: str = Form(), password: str = Form(), db: Session = Depends(get_db)):
    root = db.query(Root).filter(Root.phone == phone).first()
    if not root:
        raise HTTPException(status_code=401, detail="用户不存在")
    if not pwd_context.verify(password, root.password):
        raise HTTPException(status_code=401, detail="密码错误")
    expiration = datetime.utcnow() + timedelta(hours=24)
    token = jwt.encode({"user_id": root.id, "exp": expiration}, SECRET_KEY, algorithm="HS256")
    return {"token": token, "code": 200}


storage_path = os.path.join(os.getcwd(), 'storage/')
if not os.path.exists(storage_path):
    os.makedirs(storage_path)
@router.post("/upload")
async def upload_image(image: UploadFile = File(...)):
    unique_id = uuid.uuid4()
    file_extension = os.path.splitext(image.filename)[1]
    unique_filename = f"{unique_id}{file_extension}"
    file_path = os.path.join(storage_path, unique_filename)
    with open(file_path, "wb") as buffer:
        buffer.write(await image.read())
    return {"path": f"storage/{unique_filename}", "url": f"http://127.0.0.1:8000/storage/{unique_filename}"}

@router.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    root = db.query(Root).filter(Root.phone == form_data.username).first()
    if not root:
        raise HTTPException(status_code=401, detail="用户不存在")
    if not pwd_context.verify(form_data.password, root.password):
        raise HTTPException(status_code=401, detail="密码错误")
    expiration = datetime.utcnow() + timedelta(hours=24)
    token = jwt.encode({"user_id": root.id, "exp": expiration}, SECRET_KEY, algorithm="HS256")
    return {"access_token": token, "toke_type": "bearer", "code": 200}

@router.post("/register")
async def register_with_avatar(name: str = Form(...),
                               password: str = Form(...),
                               phone: str = Form(...),
                               password_confirm: str = Form(...),
                               avatar: UploadFile = File(None),
                               db: Session = Depends(get_db)):
    phone = re.sub(r'\D', '', phone)
    if not re.match(r'^1[3-9]\d{9}$', phone):
        raise HTTPException(status_code=400, detail="手机号格式错误")
    if password!= password_confirm:
        raise HTTPException(status_code=400, detail="两次密码不一致")
    db_root = db.query(Root).filter(Root.phone == phone).first()
    if db_root:
        db.close()
        raise HTTPException(status_code=400, detail="用户已存在")
    hashed_password = pwd_context.hash(password)
    if len(password) < 8:
        raise HTTPException(status_code=400, detail="密码长度至少为8位")
    unique_id = uuid.uuid4()
    if avatar:
        file_extension = os.path.splitext(avatar.filename)[1]
        unique_filename = f"{unique_id}{file_extension}"
        file_path = os.path.join(storage_path, unique_filename)
        with open(file_path, "wb") as buffer:
            buffer.write(await avatar.read())
        avatar_path = f"storage/{unique_filename}"
    else:
        avatar_path = None
    new_user = Root(name=name, phone=phone, password=hashed_password, avatar=avatar_path)
    db.add(new_user)
    db.commit()
    db.close()
    return {"message": "注册成功"}

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
